import {Injectable} from '@angular/core';
import CryptoJS from 'crypto-js';
import {GnUuidUtils} from '../utils';

@Injectable()
export class GnOAuthSession {

  state: string;
  codeVerifier: string;
  codeChallenge: string;

  constructor() {
    const json = sessionStorage.getItem('OAuthSession');
    if (json) {
      Object.assign(this, JSON.parse(json));
    }
  }

  refresh(): void {
    this.state = GnUuidUtils.uuid();
    this.codeVerifier = GnUuidUtils.uuid() + '-' + GnUuidUtils.uuid();
    this.codeChallenge = CryptoJS.SHA256(this.codeVerifier)
      .toString(CryptoJS.enc.Base64)
      .replace(/\+/g, '-')
      .replace(/\//g, '_')
      .replace(/=/g, '');

    sessionStorage.setItem('OAuthSession', JSON.stringify(this));
  }
}
